package com.demo.netty.http.handler;

import com.sun.jndi.toolkit.url.Uri;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;


/**
 * 1. SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapter
 * 2. HttpObject 表示客户端和服务器端相互通信的数据被封装成httpObject类型
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    /**
     * 读取客户端数据
     *
     * @param ctx 上下文
     * @param msg 消息
     * @throws Exception ex
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        String s = ctx.channel().config().getOptions().toString();
        System.out.println(s);
        if (msg instanceof LastHttpContent) {
//            System.out.println(msg);
        }
        System.out.println("this handler hashcode" + this.hashCode());
        System.out.println("this pipeline hashcode" + ctx.channel().pipeline().hashCode());
        if (!(msg instanceof HttpRequest)) {
            System.out.println("不支持的类型" + msg.getClass());
            return;
        } else {
            HttpRequest request = (HttpRequest) msg;
            //过滤特定资源
            URI uri = new URI(request.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("检测到favicon.ico 不做响应内容处理");
                return;
            }
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());

            //
            ByteBuf buf = Unpooled.copiedBuffer("hello 我是服务器", StandardCharsets.UTF_8);
            FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            resp.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";charset=UTF-8");
            resp.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
            ctx.writeAndFlush(resp);
        }
    }
}
